<?php
class Router{
	private $app = "cms";
	private $file = "index";
	private $args = "";
	private $appPath = "";

	private static $instance = NULL;

	public function __construct(){
		$url = str_replace($_SERVER['SCRIPT_NAME'],"",$_SERVER['REQUEST_URI']);
		$url = substr($url,0,1) == '/' ? substr($url,1) : $url;
		$arr = explode('/',$url);
		if( !empty($arr[0]) ){
			$this->app = $arr[0];
			unset($arr[0]);
		}
		if( !empty($arr[1]) ){
			$this->file = $arr[1];
			unset($arr[1]);
		}
		if( count($arr)>0 ){
			for($i=2;isset($arr[$i]);$i+=2){
				$tmp = empty($arr[$i+1]) ? "" : $arr[$i+1];
				$this->args .= $arr[$i].'='.$tmp;					
			}
		}
		$this->appPath = __ROOT__."app/";
	}

	public static function init(){
		if( is_null(self::$instance) ){
			self::$instance = new Router();
		}		
		return self::$instance;
	}

	public function run(){
		$file = $this->appPath.$this->app.'/'.$this->file.'.php';
		if( file_exists($file) ){
			require_once($file);
		}else{
			$this->error('unknown request');
		}
	}

	public function error($msg){
		echo $msg;
	}

	public function get($prop){
		return $this->$prop;
	}
}

